<template>
  <el-container style="height:100%;">
    <el-header
      style="line-height: 60px;text-align: start;background-color: #ccc;"
    >{{$t('access.access')}}</el-header>
    <div class="access-info-toolbar">
      <div id="arrow_div" @click="backToDsList">
        <img id="arrow_img" src="../images/arrow.png" />
        <p>
          <span id="arrow_text">{{$t('access.back')}}</span>
        </p>
      </div>
    </div>
    <el-main style="height: 80%;width: 98%;">
      <div class="access-datasource-info">
        <div class="access-datasource-info-title">{{formTitle}}</div>
        <el-row :gutter="15">
          <el-form ref="dsForm" :model="formData" :rules="rules" size="small">
            <el-form-item prop="name">
              <el-input v-model="formData.name" size="medium" clearable :style="{width: '98%'}">
                <template :style="{width: '100px'}" slot="prepend">{{$t('access.ds_name')}}</template>
              </el-input>
            </el-form-item>
            <el-form-item prop="description">
              <el-input v-model="formData.description" clearable :style="{width: '98%'}">
                <template slot="prepend">{{$t('access.ds_desc')}}</template>
              </el-input>
            </el-form-item>
            <el-form-item prop="url">
              <el-input
                v-model="formData.url"
                :placeholder="urlPlaceholder"
                clearable
                suffix-icon="el-icon-info"
                :style="{width: '98%'}"
              >
                <template slot="prepend">URL://</template>
              </el-input>
            </el-form-item>
            <el-col :span="12">
              <el-form-item prop="user">
                <el-input v-model="formData.user" clearable :style="{width: '100%'}">
                  <template slot="prepend">{{$t('access.ds_username')}}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="password">
                <el-input
                  v-model="formData.password"
                  clearable
                  show-password
                  :style="{width: '100%'}"
                >
                  <template slot="prepend">{{$t('access.ds_password')}}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="maxActive">
                <el-input v-model="formData.maxActive" clearable :style="{width: '100%'}">
                  <template slot="prepend">{{$t('access.ds_max_active')}}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="initialSize">
                <el-input v-model="formData.initialSize" clearable :style="{width: '100%'}">
                  <template slot="prepend">{{$t('access.ds_initial_size')}}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item prop="maxWait">
                <el-input v-model="formData.maxWait" clearable :style="{width: '100%'}">
                  <template slot="prepend">{{$t('access.ds_max_wait')}}</template>
                  <template slot="append">{{$t('access.min')}}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label prop="enableCheck">
                <el-checkbox-group v-model="enableCheck" size="medium">
                  <el-checkbox
                    v-for="(item, index) in enableCheckOptions"
                    :key="index"
                    :label="item.value"
                    :disabled="item.disabled"
                    style="float: left;"
                  >{{item.label}}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item size="large" class="access-datasource-info-btns">
                <el-button
                  type="primary"
                  id="access-datasource-info-btn-test"
                  @click="testConnect"
                >{{$t("access.test")}}</el-button>
                <el-button
                  type="primary"
                  id="access-datasource-info-btn-save"
                  @click="submitForm"
                >{{curMode=="edit"?$t("access.update"):$t("base.save")}}</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>
    </el-main>
  </el-container>
</template>
<script>
export default {
  components: {},
  props: [],
  data() {
    return {
      formData: {
        name: "",
        description: "",
        url: "",
        user: "",
        password: "",
        maxActive: 1000,
        initialSize: 5,
        maxWait: 5,
        enable: 0,
        enableCollection: 1,
        info: "",
        type: "mysql"
      },
      /** 数据源id */
      rsid: "",
      enableCheck: [],
      testOk: false,
      /** 页面状态：编辑edit/新建create */
      curMode: "create",
      formTitle: this.$t("access.create_ds"),
      urlPlaceholder: "",
      rules: {
        name: [
          {
            required: true,
            message: "",
            trigger: "blur"
          },
          { max: 60, message: "长度不超过60个字符", trigger: "blur" }
        ],
        desc: [
          {
            required: true,
            message: "",
            trigger: "blur"
          },
          { max: 200, message: "长度不超过200个字符", trigger: "blur" }
        ],
        url: [
          {
            required: true,
            // message: "jdbc:oracle:thin:@<host>:<port>/<sid>",
            trigger: "blur"
          }
        ],
        user: [
          {
            required: true,
            message: "",
            trigger: "blur"
          }
        ],
        password: [
          {
            required: true,
            message: "",
            trigger: "blur"
          }
        ],
        maxActive: [
          {
            required: true,
            message: ""
          },
          { type: "number", message: "请输入数字值" }
        ],
        initialSize: [
          {
            required: true,
            message: ""
          },
          { type: "number", message: "请输入数字值" }
        ],
        maxWait: [
          {
            required: true,
            message: ""
          },
          { type: "number", message: "请输入数字值" }
        ]
      },
      enableCheckOptions: [
        {
          label: "允许采集",
          value: "enableCollection"
        }
      ]
    };
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    debugger;
    //数据源编辑
    if (this.$route.query.rsid != null) {
      this.rsid = this.$route.query.rsid;
      this.curMode = "edit";
      if (this.$route.query.type != null) {
        this.formTitle =
          this.$t("base.edit") + this.$route.query.type + this.$t("access.ds");
      } else {
        this.formTitle = this.$t("access.edit_ds");
      }
      this.initForm();
    } else {
      if (this.$route.query.type != null) {
        this.formTitle =
          this.$t("access.create") +
          this.$route.query.type +
          this.$t("access.ds");
        if (this.$route.query.type == "mysql") {
          this.urlPlaceholder =
            "jdbc:mysql://<host>:<port>/<sid>?useUnicode=true&characterEncoding=utf-8&useSSL=false";
        } else if (this.$route.query.type == "oracle") {
          this.urlPlaceholder = "jdbc:orcale:thin:@<host>:<port>/<sid>";
        } else if (this.$route.query.type == "sqlserver") {
          this.urlPlaceholder =
            "jdbc:sqlserver://<host>:<port>;DatabaseName=<sid>";
        }

        this.formData.type = this.$route.query.type;
      }
    }
  },
  methods: {
    backToDsList() {
      debugger;
      this.$router
        .push({
          path: "/",
          query: {}
        })
        .catch(data => {});
    },
    initForm() {
      debugger;
      let _this = this;
      this.axios
        .post(this.HOST + "datasource/get", { id: _this.rsid })
        .then(function(res) {
          if (!res.data.success) {
            _this.$alert(res.data.messagge, "提示", {
              confirmButtonText: _this.$t("base.ok")
            });
            return;
          }
          _this.formData = res.data.data;
          /** 数据源是否采集元数据(0:不开启，1:开启) */
          if (_this.formData.enableCollection == "1") {
            _this.enableCheck.push("enableCollection");
          }
        })
        .catch(function(err) {
          _this.$message.error(_this.$t("base.operation_error") + ":" + err);
        });
    },
    submitForm() {
      let checked = true;
      this.$refs["dsForm"].validate(valid => {
        debugger;
        if (!valid) {
          console.log("error submit!!");
          checked = false;
          return false;
        }
      });
      debugger;
      if (!checked) {
        this.$message("数据源信息填写存在问题，请检查！");
        return;
      }

      if (!this.testOk) {
        this.$message("测试连接未通过！");
        return;
      }

      debugger;
      let _this = this;

      /** 数据源是否采集元数据(0:不开启，1:开启) */
      if (
        _this.enableCheck.length > 0 &&
        _this.enableCheck[0] == "enableCollection"
      ) {
        _this.formData.enableCollection = 1;
      } else {
        _this.formData.enableCollection = 0;
      }

      var requestUrl =
        _this.curMode == "create" ? "datasource/create" : "datasource/update";
      this.axios
        .post(this.HOST + requestUrl, _this.formData)
        .then(function(res) {
          if (!res.data.success) {
            _this.$alert(res.data.messagge, "提示", {
              confirmButtonText: _this.$t("base.ok")
            });
            return;
          }
          if (res.data.data.status != null && !res.data.data.status) {
            _this.$message.error(
              _this.$t("base.operation_error") + ":" + res.data.data.msg
            );
          } else {
            _this.backToDsList();
          }
        })
        .catch(function(err) {
          _this.$message.error(_this.$t("base.operation_error") + ":" + err);
        });
    },
    resetForm() {
      this.$refs["dsForm"].resetFields();
    },
    /** 测试连接 */
    testConnect() {
      let _this = this;
      // /connection-test
      this.axios
        .post(this.HOST + "datasource/connection-test", {
          url: _this.formData.url,
          user: _this.formData.user,
          password: _this.formData.password,
          type: _this.formData.type,
          info: ""
        })
        .then(function(res) {
          if (!res.data.success) {
            _this.$message.error("测试连接失败!");
            return false;
          }
          debugger;
          if (!res.data.data) {
            _this.$message.error("测试连接失败!");
            _this.testOk = false;
            return false;
          } else {
            _this.$message("测试连接成功!");
            _this.testOk = true;
            return true;
          }
        })
        .catch(function(err) {
          _this.$message.error(_this.$t("base.operation_error") + ":" + err);
        });
    }
  }
};
</script>
<style>
.access-info-toolbar {
  line-height: 60px;
  text-align: start;
  height: 40px;
  width: 98%;
  margin-top: 5px;
}
#arrow_div {
  border-width: 0px;
  position: absolute;
  left: 20px;
  width: 70px;
  height: 31px;
  cursor: pointer;
}
#arrow_img {
  border-width: 0px;
  position: absolute;
  left: 0px;
  top: 6px;
  width: 71px;
  height: 28px;
}
#arrow_text {
  border-width: 0px;
  position: absolute;
  left: 8px;
  width: 66px;
  line-height: 10px;
  word-wrap: break-word;
}
.access-datasource-info {
  height: 90%;
  width: 60%;
  text-align: center;
  display: inline-block;
}
.access-datasource-info-title {
  margin: 10px;
  font-weight: bolder;
}
.access-datasource-info-btns {
  text-align: right;
}
#access-datasource-info-btn-test {
  background-color: #00cc34;
  border: 1px solid #d6d3d3;
}
#access-datasource-info-btn-test span {
  color: #ffffff;
  font-weight: 400;
}
#access-datasource-info-btn-save {
  background-color: #f9f9f9;
  border: 1px solid #d6d3d3;
}
span {
  font-family: "Arial Normal", "Arial";
  font-weight: 400;
  font-style: normal;
  font-size: 13px;
  color: #333333;
  text-align: center;
  line-height: normal;
}
</style>
